import 'dart:async';
import 'package:base_lib/common/index.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:url_launcher/url_launcher.dart';
import '../app.dart';
import 'log.dart';

///
///                    .::::.
///                  .::::::::.
///                 :::::::::::
///             ..:::::::::::'
///           '::::::::::::'
///             .::::::::::
///        '::::::::::::::..
///             ..::::::::::::.
///           ``::::::::::::::::
///            ::::``:::::::::'        .:::.
///           ::::'   ':::::'       .::::::::.
///         .::::'      ::::     .:::::::'::::.
///        .:::'       :::::  .:::::::::' ':::::.
///       .::'        :::::.:::::::::'      ':::::.
///      .::'         ::::::::::::::'         ``::::.
///  ...:::           ::::::::::::'              ``::.
/// ```` ':.          ':::::::::'                  ::::..
///                    '.:::::'                    ':'````..
///
/// Created by Wongxd on 2020/5/19.
/// https://github.com/wongxd
/// wxd1@live.com
///
class Utils {
  static String getTimeStr(DateTime date,
      {bool isShowTime = false,
      String split = "-",
      bool isDayMonthYear = false}) {
    String timestamp =
        "${isDayMonthYear ? "${date.day.toString().padLeft(2, '0')}$split${date.month.toString().padLeft(2, '0')}$split${date.year.toString()}" : "${date.year.toString()}$split${date.month.toString().padLeft(2, '0')}$split${date.day.toString().padLeft(2, '0')}"}"
        "${isShowTime ? " ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}" : ""}";
    return timestamp;
  }

  /// 打开URL连接
  static Future<bool> openUrlLink(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
      return Future.value(true);
    }
    return Future.value(false);
  }

  ///
  ///格式成 00:00:00 格式的时间
  ///time - 10位或13位的时间戳
  ///
  static String parserTime(int time) {
    String _unitFormat(int i) {
      String retStr = "";
      if (i >= 0 && i < 10)
        retStr = "0" + i.toString();
      else
        retStr = i.toString();
      return retStr;
    }

    if (time.toString().length == 10) {
      time = time * 1000;
    }
    time = time ~/ 1000;
    String timeStr = "";
    int hour = 0;
    int minute = 0;
    int second = 0;
    if (time <= 0)
      return "00:00";
    else {
      minute = time ~/ 60;
      if (minute < 60) {
        second = time % 60;
        timeStr = _unitFormat(minute) + ":" + _unitFormat(second);
      } else {
        hour = minute ~/ 60;
        if (hour > 99) return "99:59:59";
        minute = minute % 60;
        second = time - hour * 3600 - minute * 60;
        timeStr = _unitFormat(hour) +
            ":" +
            _unitFormat(minute) +
            ":" +
            _unitFormat(second);
      }
    }
    return timeStr;
  }

  ///用内置浏览器打开 url
  static void jump2WebView(
      BuildContext context, String title, String url) async {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return WebViewPage(
        title: title,
        url: url,
      );
    }));
  }

  ///用系统浏览器打开 url
  static void launchUrlBySys(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

  /// 呼叫 某号码
  static void call(String phoneNum) async {
    final String url = "tel:$phoneNum";
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not call $url';
    }
  }

  /// 向 某号码 发送短信
  static void sendSMS(String phoneNum) async {
    final String url = "sms:$phoneNum";
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not send to $url';
    }
  }

  /// 向 某号码 发送邮件
  ///
  /// mailto:smith@example.org?subject=News&body=New%20plugi
  ///
  static void sendEMAIL(String eMailAdress) async {
    final String url = "mailto:$eMailAdress";
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not send to $url';
    }
  }

  ///可以统一控制展示与否的控制台打印
  static void log(Object obj) {
    if (kReleaseMode) {
      return;
    }
    FLog(obj);
  }

  ///信息太长,分段打印
  static void logLong(Object object, {String tag = " TaoZi "}) {
    if (kReleaseMode) {
      return;
    }
    String msg = "$object";
    var pre = tag + "--";
    log(pre + '-' * 100);
    //因为String的length是字符数量不是字节数量所以为了防止中文字符过多，
    var maxStrLength = 800 - pre.length;
    //大于 maxStrLength 时
    while (msg.length > maxStrLength) {
      log(msg.substring(0, maxStrLength));
      msg = msg.substring(maxStrLength);
    }
    //剩余部分
    log(msg);
    log(pre + '-' * 100);
  }

  ///关闭最后一个 flutter 页面 ， 如果是原生跳过来的则回到原生，否则关闭app
  static void finishDartPageOrApp() {
    SystemNavigator.pop();
  }

  ///收起键盘
  static void hideSoftKeyboard(BuildContext context) {
    ///触摸收起键盘
    FocusScope.of(context).requestFocus(new FocusNode());
  }

  ///显示  context 对应  控件的尺寸
  static Size showSizes(BuildContext currentContext) {
    RenderBox renderBoxRed = currentContext.findRenderObject();
    Size r = Size(0, 0);
    try {
      r = renderBoxRed.size;
    } catch (e) {
      log(e);
    }
    log(r);
    return r;
  }

  ///显示  context 对应  控件的位置
  static Offset showPositions(BuildContext currentContext) {
    RenderBox renderBoxRed = currentContext.findRenderObject();
    Offset o = Offset(0, 0);
    try {
      o = renderBoxRed.localToGlobal(Offset.zero);
    } catch (e) {
      log(e);
    }
    log(o);
    return o;
  }

  ///修改系统状态栏颜色
  static void setStatusBarColor(Color color) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      systemNavigationBarColor: color, // navigation bar color
      statusBarColor: color, // status bar color
    ));
  }

  ///设置主题
  static void setStyle(SystemUiOverlayStyle style) {
    SystemChrome.setSystemUIOverlayStyle(style);
  }

  /// 返回性别根据数字
  static String returnGenderByInt(int sex) {
    if (sex == 1) {
      return '男';
    } else if (sex == 2) {
      return '女';
    } else {
      return '其他';
    }
  }

  /// 身份证计算出生日期 511325199002132919
  static String returnBirthday(String idCard) {
    if (idCard.length == 18) {
      var year = idCard.substring(6, 10);
      var mouth = idCard.substring(10, 12);
      var day = idCard.substring(12, 14);
      return year + "-" + mouth + "-" + day;
    } else {
      return "";
    }
  }
}
